package handler

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"go.uber.org/zap"
	"gopkg.in/fatih/set.v0"
	"net/http"
	"seichat/middlerware"
	"seichat/models"
	"seichat/service"
	"strconv"
	"sync"
)

type HandleMessage struct {
	mesSvc service.MessageService
}

// 映射关系
var clientMap map[int64]*models.Node = make(map[int64]*models.Node, 0)

var rwLocker sync.RWMutex

func (h *HandleMessage) RegisterRoutes(router *gin.Engine) {
	u := router.Group("/user")
	{
		u.Use(middlerware.JWT())
		u.GET("/send", h.Chat)
	}
}

func NewHandlerMessage(mesSvc service.MessageService) *HandleMessage {
	return &HandleMessage{
		mesSvc: mesSvc,
	}
}
func (h *HandleMessage) Chat(ctx *gin.Context) {
	// 从 gin.Context 中获取底层 *http.Request
	r := ctx.Request

	// 获取查询参数
	query := r.URL.Query()
	idStr := query.Get("userId")

	// 转换为 int64
	userId, err := strconv.ParseInt(idStr, 10, 64)
	if err != nil {
		zap.S().Errorw("类型转换失败", "error", err, "input", idStr)
		ctx.AbortWithStatusJSON(http.StatusBadRequest, gin.H{
			"error": "invalid userId",
		})
		return
	}
	// 升级为 WebSocket 连接
	var invalidism = true
	upgrade := websocket.Upgrader{
		CheckOrigin: func(r *http.Request) bool {
			return invalidism
		},
	}

	conn, err := upgrade.Upgrade(ctx.Writer, r, nil)
	if err != nil {
		fmt.Println(err)
		ctx.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{
			"error": "WebSocket upgrade failed",
		})
		return
	}
	//获取socket连接,构造消息节点
	node := &models.Node{
		Conn:      conn,
		DataQueue: make(chan []byte, 50),
		GroupSets: set.New(set.ThreadSafe),
	}

	//将userId和Node绑定
	rwLocker.Lock()
	clientMap[userId] = node
	rwLocker.Unlock()

	//服务发送消息
	go h.mesSvc.SendProc(node)

	//服务接收消息
	go h.mesSvc.RecProc(node)
	//sendMsg(userId, []byte("欢迎进入聊天系统"))
}
